package creator.ui.controller;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class VoicePlayer {

  public static void play(String voicePath) {
    new Thread(
      new Runnable(voicePath) {
        public void run() {
          try {
            String voiceURI =
              VoicePlayer.class.getResource(VoicePlayer.this).getPath();

            File voiceFile = new File(
              voiceURI.replace("file:/", "").replace("FlappyBird.jar!/", "")
            );
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(
              voiceFile
            );

            AudioFormat audioFormat = audioInputStream.getFormat();

            DataLine.Info dataLineInfo = new DataLine.Info(
              SourceDataLine.class,
              audioFormat,
              -1
            );
            SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(
              dataLineInfo
            );
            sourceDataLine.open(audioFormat);
            sourceDataLine.start();

            byte[] tempBuffer = new byte[1024];
            int count;
            while (
              (
                count = audioInputStream.read(tempBuffer, 0, tempBuffer.length)
              ) !=
              -1
            ) {
              int count;
              if (count > 0) {
                sourceDataLine.write(tempBuffer, 0, count);
              }
            }

            sourceDataLine.drain();
            sourceDataLine.close();
          } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          } catch (LineUnavailableException e) {
            e.printStackTrace();
          }
        }
      }
    )
      .start();
  }
}
